{% load static %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>ChatBot</title>

    <link rel="stylesheet" href="{% static 'layim/css/layui.css' %}">
    <style>
        html {
            background-color: #333;
        }

        .link-to-send {
            cursor: pointer;
            color: #1E9FFF;
        }
    </style>
</head>
<body>

<script src="{% static 'layim/layui.js' %}"></script>
<script src="{% static 'js/jquery.js' %}"></script>
<script src="{% static 'js/js.cookie.js' %}"></script>
<script>
    String.prototype.format = function (args) {
        let result = this;
        if (arguments.length > 0) {
            if (arguments.length === 1 && typeof (arguments) == "object") {
                for (const key in args) {
                    if (args[key] !== undefined) {
                        const reg = new RegExp('\\{' + key + '\\}', 'gm')
                        result = result.replace(reg, args[key]);
                    }
                }
            } else {
                for (let i = 0; i < arguments.length; i++) {
                    if (arguments[i] !== undefined) {
                        const reg = new RegExp("({[" + i + "]})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
        }
        return result;
    }

    let search = window.location.search
    let name = 'channel'
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    let r = search.substr(1).match(reg);  //匹配目标参数
    if (r != null)
        channel = unescape(r[2])
    else
        channel = null
    let tempUrl = '{% url "chatbot" 1111 %}'
    let chatbotUrl = tempUrl.replace('1111', channel)
    let chatbotImageUpload = '{% url "chatbot-upload-img" %}'
    let csrftoken = Cookies.get('csrftoken');
    let robot_info, visitor_info, tenant_info, greetings, greeting_recommend_info

    $.ajax({
        type: 'get',
        url: chatbotUrl,
        async: false,
        //成功的回调函数
        success: function (data) {
            robot_info = data.robot_info
            visitor_info = data.visitor_info
            tenant_info = data.tenant_info
            greetings = data.greetings
            greeting_recommend_info = data.greeting_recommend_info
        },
        //失败的回调函数
        error: function (e) {
            robot_info = {name: '111', avatar: ''}
            console.error(e)
        }
    })

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    function getClickToSendEl(text, seq) {
        let showText = text
        if (seq !== undefined)
            showText = '{0}.{1}'.format(seq, text)
        return '<div layim-event="linkToSend" lay-text="{0}" class="link-to-send">{1}</div>'.format(text, showText)

    }

    robot_id = 'robot_' + tenant_info.tenant_id
    visitor_id = 'visitor_' + visitor_info.id
    robot_obj = {
        username: robot_info.name
        , avatar: robot_info.avatar
        , id: robot_id
        , type: 'kefu'
    }
    visitor_obj =
        layui.use('layim', function (layim) {
                layim.config({
                    init: {
                        //配置客户信息
                        mine: {
                            "username": visitor_info.name //我的昵称
                            , "id": 'visitor_' + visitor_id//我的ID
                            , "status": "online" //在线状态 online：在线、hide：隐身
                            , "remark": "在深邃的编码世界，做一枚轻盈的纸飞机" //我的签名
                            , "avatar": visitor_info.avatar //我的头像
                        }
                    }
                    //开启客服模式
                    , brief: true
                    , isAudio: true
                    , isVideo: true
                    //上传图片接口（返回的数据格式见下文），若不开启图片上传，剔除该项即可
                    , uploadImage: {
                        url: chatbotImageUpload //接口地址
                        , type: 'post' //默认post
                    }

                    //上传文件接口（返回的数据格式见下文），若不开启文件上传，剔除该项即可
                    , uploadFile: {
                        url: '' //接口地址
                        , type: 'post' //默认post
                    }
                    //扩展工具栏，下文会做进一步介绍（如果无需扩展，剔除该项即可）
                    , tool: [{
                        alias: 'code' //工具别名
                        , title: '代码' //工具名称
                        , icon: '&#xe64e;' //工具图标，参考图标文档
                    }]
                    , chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html'
                });

                //打开一个客服面板
                layim.chat({
                    name: tenant_info.name //名称
                    , type: 'kefu' //聊天类型
                    , avatar: tenant_info.logo //头像
                    , id: robot_id //定义唯一的id方便你处理信息
                });


                let has_visited = sessionStorage.getItem('visited')
                if (has_visited !== '1') {
                    greetings.forEach(function (item) {
                        robot_obj.content = item
                        layim.getMessage(robot_obj)
                    })
                    sessionStorage.setItem('visited', '1')

                    // 欢迎语推荐问题
                    if (JSON.stringify(greeting_recommend_info) !== '{}') {
                        let {recommend_script, questions} = greeting_recommend_info
                        if (questions !== undefined && questions.length !== 0) {

                            let content = '<div>{0}</div>'.format(recommend_script)
                            questions.forEach(function (item, index) {
                                content += getClickToSendEl(item, index + 1)
                            })
                            robot_obj.content = content
                            layim.getMessage(robot_obj)
                        }
                    }
                }


                layim.on('sendMessage', function (data) {
                    let To = data.to;
                    console.log(To);

                    //发送消息倒Socket服务
                    /*
                    socket.send({
                      type: 'chatMessage'
                      ,content: data.mine.content
                    });
                    */

                    $.ajax({
                        type: 'POST',
                        url: chatbotUrl,
                        data: JSON.stringify({
                            'text': data.mine.content
                        }),
                        contentType: 'application/json',
                        //成功的回调函数
                        success: function (answer) {
                            robot_obj.content = answer.answer
                            layim.getMessage(robot_obj);
                        },
                        //失败的回调函数
                        error: function () {
                            robot_obj.content = "我现在思考人生哦"
                            layim.getMessage(robot_obj);
                            console.log("error")
                        }
                    })
                });
                layim.on('tool(code)', function (insert) {
                    layer.prompt({
                        title: '插入代码'
                        , formType: 2
                        , shade: 0
                    }, function (text, index) {
                        layer.close(index);
                        insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
                    });
                });
            }
        )
    ;


    layui.use(['code'], function () {
        layui.code({
            elem: 'pre'
        })
    });

</script>
</body>
</html>
